package com.example.wenqujingdian.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.WindowManager;
import android.webkit.ConsoleMessage;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.example.wenqujingdian.R;
import com.example.wenqujingdian.api.ApiConfig;
import com.example.wenqujingdian.conast.AudioKey;
import com.example.wenqujingdian.utils.MD5Util;
import com.example.wenqujingdian.utils.ToastUtil;
import com.vise.utils.handler.HandlerUtil;
import com.vise.xsnow.http.ViseHttp;
import com.vise.xsnow.http.callback.ACallback;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.jessyan.autosize.internal.CancelAdapt;

public class WebView2Activity extends BaseActivity {
    private static final String TAG = "WebViewActivity";
    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.webViewFrameLayout)
    FrameLayout frameLayout;
    private String flag;
    private String linkAddress;
    private String urlXxls;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        ButterKnife.bind(this);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
       /* if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        } else {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }*/
        initView();
    }


    private String webUrl = "";

    private void initView() {

        flag = getIntent().getStringExtra("flag");
        linkAddress = getIntent().getStringExtra("linkAddress");
        urlXxls = getIntent().getStringExtra("url");
        if (linkAddress != null) {
            initWebView(linkAddress);
            return;
        }

        switch (flag) {
            case "1":
                String url = getIntent().getStringExtra("url");
                initWebView("http://m.wenqujingdian.com" + url);
                break;
            case "2":
                webUrl = ApiConfig.POLICY_URL;
                initWebView(webUrl);
                break;
            case "3":
                Log.i(TAG, "onViewClicked: 风彩展示");
                webUrl = "http://www.wenqujingdian.com/index.php/Fengcai";
                initWebView(webUrl);
                break;
            case "13":
                Log.i(TAG, "onViewClicked: 阅读活动");
                webUrl = "http://www.wenqujingdian.com/index.php/Tushu/index/lm/469.shtml";
                initWebView(webUrl);
                break;
            case "5"://期刊
                webUrl = "http://vertical.591adb.com/wqjd.html";
                initWebView(webUrl);
                break;
            case "6":
                Log.i(TAG, "onViewClicked: 音频");
                webUrl = "http://wenqujingdian.com/index.php/Yinpin";
                //shouQuan();
                initWebView(webUrl);
                break;
            case "7":
                Log.i(TAG, "onViewClicked: 报纸");
                webUrl = "http://wenqujingdian.com/index.php/Baozhi";
                initWebView(webUrl);
                break;
            case "8":
                Log.i(TAG, "onViewClicked: 视频");
                webUrl = "http://wenqujingdian.com/index.php/Video";
                initWebView(webUrl);
                break;
            case "9":
                Log.i(TAG, "onViewClicked: 党政专题");
                webUrl = "http://wenqujingdian.com/index.php/Tushu/index/lm/439.shtml";
                initWebView(webUrl);
                break;
            case "10":
                Log.i(TAG, "onViewClicked: 国学新读");
                webUrl = "http://wenqujingdian.com/index.php/Guoxue";
                initWebView(webUrl);
                break;
            case "11":
                Log.i(TAG, "onViewClicked: 健康养生");
                webUrl = "http://wenqujingdian.com/index.php/Tushu/index/lm/440.shtml";
                initWebView(webUrl);
                break;
            case "12":
                Log.i(TAG, "onViewClicked: 创业创新");
                webUrl = "http://wenqujingdian.com/index.php/Tushu/index/lm/441.shtml";
                initWebView(webUrl);
                break;

            case "23"://书香校园版 纠错宝
//                webUrl = "http://ceping.wenqujingdian.com/pailei/step1.html";
                webUrl = "http://ceping.wenqujingdian.com/api.aspx";
                initWebView(webUrl);
                break;
            case "24"://书香校园版 新教学
                webUrl = "http://www.wenqujingdian.com/index.php/Tushu/index/lm/471.shtml";
                initWebView(webUrl);
                break;
            case "25"://书香校园版 微课
                webUrl = "http://wqjd.wowxue.com/";
                initWebView(webUrl);
                break;
            case "55":
                webUrl = "http://wenqujingdian.com/index.php/Tushu/index/lm/472.shtml";
                initWebView(webUrl);
                break;
            case "111":
                webUrl = "http://wqjd.80community.com/api.aspx";
                initWebView(webUrl);
                break;
            case "112":
                webUrl = "http://wqjd.wowxue.com/";
                initWebView(webUrl);
                break;
            case "113":
                webUrl = "http://www.wenqujingdian.com/index.php/Tushu/index/lm/471.shtml";
                initWebView(webUrl);
                break;
            case "1057":
                webUrl = "http://wap.cnki.net/touch/web/guide";
                initWebView(webUrl);
                break;
            case "1058":
                webUrl = "http://www.baidu.com";
                initWebView(webUrl);
                break;
            case "1076"://3d图书
                webUrl = "file://" + getIntent().getStringExtra("url");
                initWebView(webUrl);
                break;
            case "1088"://学习路上
                webUrl = urlXxls;
                initWebView(webUrl);
                break;
            case "888"://c测试
                webUrl = "http://oss.wenqujingdian.com/pages/hd/szdh/index.html";
                initWebView(webUrl);
                break;
            case "1105"://球球绘本
                webUrl = "http://www.qiuqiuhuiben.com/homepage/search.html";
                initWebView(webUrl);
                break;
            case "1106"://学习强国
                webUrl = "https://www.xuexi.cn/";
                initWebView(webUrl);
                break;
        }


    }

    private String App_key = "fed82efeba2963ddb349a351726a33b2";
    private String Identify_key = "3d6c567b5ea821a17df9ecd26a42a98e";
    private int Type_id = 1;
    private String userId = "123";
    private String sign_code;

    private void shouQuan() {
        ViseHttp.CONFIG().baseUrl("http://api.183read.cc");

        sign_code = MD5Util.getMd5(MD5Util.getMd5(Identify_key) + MD5Util.getMd5(userId));
        //Log.i(TAG, "initView: sign_code=" + sign_code);


        String url = "/open_api/rest2.php?act=module.user.session.great&param={" +
                "\"identify_key\":" + "\"" + Identify_key + "\"," +
                "\"app_key\":" + "\"" + App_key + "\"," +
                "\"user_id\":" + "\"" + userId + "\"," +
                "\"sign_code\":" + "\"" + sign_code + "\"," +
                "\"type_id\":" + "\"" + Type_id + "\"" +
                "}";


        ViseHttp.GET(url)
                .tag(TAG)
                //.addParam("username", strPhone)
                // .addParam("password", strPassword)
                .request(new ACallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        // NiceDialogUtils.dismissNiceDialog();
                        Log.i(TAG, "onSuccess: result=" + result);

                        webUrl = "http://wenqujingdian.com/index.php/Yinpin?user_id=" + userId;
                        initWebView(webUrl);
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        // NiceDialogUtils.dismissNiceDialog();
                        //请求失败，errCode为错误码，errMsg为错误描述
                        ToastUtil.showToast("errCode=" + errCode + " errMsg=" + errMsg);
                    }
                });
    }

    private void startSystemExplorer(Uri uri) {

        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }

    //private List<String> loadHistoryUrls = new ArrayList<String>();

    private void initWebView(final String webUrl) {


        webView.loadUrl(webUrl);
        Log.i(TAG, webUrl + "-----------------");
        WebSettings webSettings = webView.getSettings();

        webSettings.setJavaScriptEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.setWebContentsDebuggingEnabled(true);
        }
        webSettings.setMediaPlaybackRequiresUserGesture(true);
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        // 开启支持视频
        webView.getSettings().setDomStorageEnabled(true);
        webSettings.setPluginState(WebSettings.PluginState.ON);
        webView.setWebChromeClient(new WebChromeClient());
        webView.setInitialScale(100);   //100代表不缩放
        webView.addJavascriptInterface(this, "webView");

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                Log.e("webview日志", consoleMessage.message());
                return super.onConsoleMessage(consoleMessage);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                //使弹窗变toast
                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
                result.confirm();
                return true;
            }

        });
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url == null) return false;

                try {
                    if (!url.startsWith("http://") //
                            && !url.startsWith("https://")
                    ) {
                        //不是规范开头直接returnfalse
                        return false;
                    }
                } catch (Exception e) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                    Log.i("加载资源", "异常");
                    return true;//没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
                }
                Log.i("加载资源", url);
                view.loadUrl(url);
                return true;
            }


            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (!zhuRu(view, url)) {
                    //ToastUtil.showToast("网站url为: " + url);
                } else {
                    ToastUtil.show("语音功能已启用");
                }
            }
        });

    }


    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            if (flag.equals("7")) {
                super.onBackPressed();
            } else {
                webView.goBack();
            }

        } else {
            this.finish();
        }

    }

    //区分注入方式
    public boolean zhuRu(WebView webView, String url) {
        HashMap<String, String> urlMap = new HashMap<>();
        //期刊
        urlMap.put("vertical.591adb.cn/journal/article", "qikan");
        urlMap.put("vertical.591adb.cn/dynamic/article", "qikan");


        Set<String> keys = urlMap.keySet();
        for (String key : keys) {
            if (url.contains(key)) {
                //执行特殊注入
                //ToastUtil.show("适配语音注入成功");
                loadLocalJS(webView, "jquery.min");
                loadLocalJS(webView, "baseDuBao");
                loadLocalJS(webView, urlMap.get(key));
                return true;
            }
        }
        return false;

    }

    public String getFromAssets(String fileName) {
        try {
            InputStreamReader inputReader = new InputStreamReader(getResources().getAssets().open("duBaoScript/" + fileName));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            String Result = "";
            while ((line = bufReader.readLine()) != null) {
                if (!line.trim().startsWith("//")) {
                    Result += line + "\n";
                }
            }
            return Result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //注入本地js
    public void loadLocalJS(WebView webView, String jsFileName) {
        String js = getFromAssets(jsFileName + ".js");
        if (null == js) {
            ToastUtil.show("读取出错");
        }
        Log.e("注入js", js.replace("\n", ""));
        webView.loadUrl("javascript:" + js);
    }


    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        frameLayout.removeView(webView);
        webView.setFocusable(true);
        webView.removeAllViews();
        webView.clearHistory();
        webView.destroy();
    }


    @JavascriptInterface
    public String getKey() {
        return AudioKey.key;
    }
}